const { json } = require("express");
let express = require("express");

let Router = express.Router(); //获取Router对象用于开启路由 Router==app，比app对象多了路由管理功能
let mongo = require("../../db/mongo");
let { create, verify } = require("./token");
let { ObjectId } = require("mongodb");
let upload = require("./multer");
let config = require("../../config.json");
/*
    用户管理相关接口：
        * 验证用户名是否存在 get
        * 注册 post
        * 登录 get 7天免登录
        * 验证 token
        * 查询列表 get
        * 删除用户 delete
        * 修改密码 put
        * 上传头像 post
        * 查询某个用户信息 get
*/

//验证用户名是否存在 get
Router.get("/checkname", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    // let { name } = req.query; //{name:'王祖贤'}
    // console.log(name, 888);
    let p = await mongo.find({
      colname: "user",
      query: req.query,
    });
    // console.log(p, 999);

    if (p.length) {
      //不为零:已存在,不能注册
      data = {
        code: 3000,
        flag: false,
        message: "账号已存在，请换一个用户名",
      };
    } else {
      //不存在，可以注册
      data = {
        code: 2000,
        flag: true,
        message: "允许注册",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
});

//注册 post
Router.post("/reg", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    // let { name, password } = req.body;//{name:'王祖贤',password:123456}
    let arr = [];
    arr.push(req.body);
    let p = await mongo.insert({
      colname: "user",
      data: arr, //[{}]
    });
    console.log(p, 678);

    if (p.flag) {
      //不为零:注册成功
      data = {
        code: 2000,
        flag: true,
        message: "注册成功",
      };
    } else {
      //注册失败
      data = {
        code: 3000,
        flag: false,
        message: "注册失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
  //   res.send("666");
});

//登录 get 7天免登录
Router.get("/login", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { name, password } = req.query;
    // console.log(name, 888);
    let p = await mongo.find({
      colname: "user",
      query: req.query,
    });
    // console.log(p);

    if (p.length) {
      //不为零:可以登录
      data = {
        code: 2000,
        flag: true,
        message: "登录成功",
        token: create(password),
      };
    } else {
      //登录失败
      data = {
        code: 3000,
        flag: false,
        message: "登录失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }
  res.send(data);
});

//校验token
Router.get("/verify", (req, res) => {
  //   console.log("测试");
  let data = {};

  let { token } = req.query;
  // console.log(name, 888);
  let result = verify(token);
  if (result) {
    //校验通过
    data = {
      code: 2000,
      flag: true,
      message: "校验通过",
    };
  } else {
    //校验失败
    data = {
      code: 3000,
      flag: false,
      message: "校验失败",
    };
  }

  res.send(data);
});

//查询列表
Router.get("/userlist", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { page, pagesize, query } = req.query;
    // console.log(name, 888);
    console.log(typeof query, query, 999);
    query = JSON.parse(query);
    console.log(typeof query, query, 888);
    let p = await mongo.find({
      colname: "user",
      query,
      page,
      pagesize,
    });
    console.log(p, 888999);

    let total = await mongo.findtotal({
      colname: "user",
      query,
    });
    // console.log(total.length, 899);
    if (p.length) {
      //查到数据
      data = {
        code: 2000,
        flag: true,
        message: "查询成功",
        page,
        pagesize,
        total: total.length,
        pages: Math.ceil(total.length / pagesize),
        data: p,
      };
    } else {
      //登录失败
      data = {
        code: 3000,
        flag: false,
        message: "查询失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }
  res.send(data);
});

//删除用户
Router.delete("/del", async (req, res) => {
  //   console.log("测试");
  let data = {};
  let { id } = req.body; //5f6bfbd41b2d855394b7f38f
  id = ObjectId(id); //ObjectId("5f6bfbd41b2d855394b7f38f"
  try {
    let p = await mongo.remove({
      colname: "user",
      query: {
        _id: id,
      },
    });
    // console.log(p, 678);

    if (p.flag) {
      //不为零:删除成功
      data = {
        code: 2000,
        flag: true,
        message: "删除成功",
      };
    } else {
      //删除失败
      data = {
        code: 3000,
        flag: false,
        message: "删除失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }
  res.send(data);
  //   res.send("666");
});

//修改用户信息
Router.put("/edit/:id", async (req, res) => {
  //   console.log("测试");
  let data = {};
  let { id } = req.params;
  id = ObjectId(id); //ObjectId("5f6bfbd41b2d855394b7f38f"
  try {
    let p = await mongo.update({
      colname: "user",
      query: {
        _id: id,
      },
      data: req.body,
    });
    // console.log(p, 678);

    if (p.flag) {
      //不为零:修改成功
      data = {
        code: 2000,
        flag: true,
        message: "修改成功",
      };
    } else {
      //修改失败
      data = {
        code: 3000,
        flag: false,
        message: "修改失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }
  res.send(data);
  //   res.send("666");
});

//上传头像
Router.post("/headpic", upload.single("avatar"), async (req, res) => {
  let str = req.file.path.replace(/\\/, "/");
  // console.log(req.body, 666);
  let url = config.URL + str;
  // console.log(req.file.path, 888);
  // console.log(url, 777);
  let data = {};
  try {
    let { id } = req.body;
    id = ObjectId(id);
    let p = await mongo.update({
      colname: "user",
      query: { _id: id },
      data: { pic: url },
    });

    if (p.flag) {
      //不为零:修改成功
      data = {
        code: 2000,
        flag: true,
        message: "上传成功",
      };
    } else {
      //修改失败
      data = {
        code: 3000,
        flag: false,
        message: "上传失败",
      };
    }
  } catch (err) {
    console.log("出错");
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }
  res.send(data);
});

//查询某个用户信息
Router.get("/getuser/:_id", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { _id } = req.params;
    _id = ObjectId(_id);
    let p = await mongo.find({
      colname: "user",
      query: { _id },
    });
    // console.log(p, 999);

    if (p.length) {
      //不为零:已存在,不能注册
      data = {
        code: 3000,
        flag: false,
        data: p,
      };
    } else {
      //不存在，可以注册
      data = {
        code: 2000,
        flag: true,
        message: "查询失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
});
module.exports = Router;
